package com.nuan.shiro.config;

import com.alibaba.fastjson.JSON;
import com.nuan.shiro.constants.CodeEnum;
import com.nuan.shiro.constants.ResultUtil;
import com.nuan.shiro.utils.WebUtilsPro;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * 直接配置路径权限
 */
public class PermissionsOAuthorizationFilter extends AuthorizationFilter
{
    public PermissionsOAuthorizationFilter() {
    }
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException
    {
        Subject subject = this.getSubject(request, response);
        String[] perms = (String[])((String[])mappedValue);
        boolean isPermitted = true;
        if (perms != null && perms.length > 0) {
            if (perms.length == 1) {
                if (!subject.isPermitted(perms[0])) {

                    isPermitted = false;
                }
            } else if (!subject.isPermittedAll(perms)) {
               for(String prem : perms){
                   if(subject.isPermitted(prem)){
                       return true;
                   }
                   if(!subject.isPermitted(prem)){
                       isPermitted=false;
                   }
               }
            }
        }
        return isPermitted;
    }

    /**
     * 拦截拒绝后使用
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        //获取请求token，如果token不存在，直接返回401
        WebUtilsPro.writer(ResultUtil.error(CodeEnum.AUTH_FAIL),request,response);
        return false;
    }

}